package com.gupaoedu.vip.netty.io.bio;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @program:gupaoedu-vip-netty-io
 * @description:同步阻塞IO模型
 * @author:Gongchao
 * @date:2020-04-27
 **/
public class BIOServer {

    //服务端网络IO模型的封装对象
    ServerSocket serverSocket;

    public BIOServer(int port) {
        try {
            //Tomcat 默认端口8080
            //redis 6379
            //zookeeper 2181
            //HBase
            //RMI
            serverSocket = new ServerSocket(port);
            System.out.println("BIO服务已启动，监听端口是："+port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /* *
     *
     * 开始监听，并处理逻辑
     * @param:[]
     * @return:void
     * @author:Gongchao
     * @date:2020-四月-27
     *
     */
    public void listen() throws IOException {
        //循环监听
        while(true) {
            //等待客户端连接，阻塞方法
            //Socket数据发送者在服务端的引用
            Socket socket = serverSocket.accept();
            System.out.println(socket.getPort());
            //客户端通过网络把数据发送到网卡，将机器所得到的数据读入到jvm中
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len = inputStream.read(bytes);
            if(len > 0) {
//                String msg = new String(bytes,0,len); 未设置编码，当输入的数据有中文时候，会出现乱码
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byteArrayOutputStream.write(bytes,0,len);
                String msg = byteArrayOutputStream.toString("UTF-8");
                System.out.println("收到:"+msg);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new BIOServer(8080).listen();
    }
}
